import alertFill from "@/assets/image/icons/alert-fill.svg";
import FileUpload from "@/assets/image/patterns/File Upload.png";
import upload from "@/assets/image/patterns/Upload.png";
import CustomModal from "@/components/customModal";
import { CloseOutlined } from "@ant-design/icons";
import AlertCircle from "@/assets/image/icons/alert-circle.svg";
import {
  ProFormCheckbox,
  ProFormText,
  ProFormUploadDragger,
} from "@ant-design/pro-components";
import { Collapse, Switch, Card, Modal, Divider, Col, Row } from "antd";
import { CheckboxChangeEvent } from "antd/es/checkbox";
import React, { useState } from "react";
import "./index.less";
import UploadDragger from "./upload-dragger";
import qualifiedDocument from "@/assets/image/Qualified Document.png";
import unqualifiedDocument from "@/assets/image/Unqualified Document.png";
import styled from "styled-components";
import { StyledNone, UploadTitle } from "../common-styled";
import LabelToolTip from "../label-tooltip/LabelToolTip";
import CustomAlert from "../customAlert";
const { Panel } = Collapse;
interface Props {
  leftText?: string;
  formName?: string;
  icon?: string;
  clickout?: () => void;
  // 是否显示删除的modal
  isDelLPN?: boolean;
  approvalStatus?: string;
  onStateDelChange?: (value: boolean) => void;
  fileList?: File;
}

// 主容器样式
export const FileContainer = styled.div`
  display: flex;
  align-items: center;
`;

// 图片样式
export const FileImage = styled.img`
  height: 64px;
  width: 64px;
  margin-right: 12px;
`;

// 文件信息容器样式
export const FileInfo = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  gap: 6px;
`;

// 文件名样式
export const FileName = styled.div`
  font-family: Roboto;
  font-size: 14px;
  font-weight: 400;
  line-height: 21px;
  color: #998065;
  text-decoration: underline;
  max-width: 300px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
`;

// 文件大小样式
export const FileSize = styled.div`
  /* styleName: 10 Footnote EN/Regular; */
  font-family: Roboto;
  font-size: 12px;
  font-weight: 400;
  line-height: 18px;
  color: #abadaf;
`;

const UploadItem: React.FC<Props> = ({
  leftText,
  icon,
  formName,
  clickout,
  isDelLPN,
  approvalStatus,
  onStateDelChange,
  // filelist 默认文件
  fileList,
}) => {
  console.log(formName, "formName");
  console.log(fileList, "fileList1111");
  const [showContent, setShowContent] = useState(false);
  const [showContent1, setShowContent1] = useState(false);
  const [collapsed, setCollapsed] = useState(isDelLPN ? false : true);
  const [isUploaded, setIsUploaded] = useState(false);
  console.log(isUploaded, "isUploaded");
  const [fileSize, setFileSize] = useState("");
  // 控制确认删除上传文件模态框的显示状态
  const [isModalOpenUnregister, setIsModalOpenUnregister] = useState(false);
  const [isModalOpenDel, setIsModalOpenDel] = useState(false);
  const [isModalOpenViewDoc, setIsModalOpenViewDoc] = useState(false);

  // Modification Limit Exceeded
  const [isModalOpenModifyLimit, setIsModalOpenModifyLimit] = useState(false);

  // todo 车牌号临时值测试弹框
  // const [initialValue] = useState("XC5689");
  // 当前车牌号值
  // const [currentValue, setCurrentValue] = useState(initialValue);
  //是否展示Modification Limit Exceeded弹框（只弹一次？）
  const [isShowModifyLimitModal, setIsShowModifyLimitModal] = useState(true);

  const handleCheckboxChange = (event: CheckboxChangeEvent) => {
    console.log(event, "checked");
    setShowContent(!!event.target.checked);
  };

  const handleCheckboxChange1 = (event: CheckboxChangeEvent) => {
    console.log(event, "checked");
    setShowContent1(!!event.target.checked);
  };

  // Unregister Modal
  const handleOkUnregister = () => {
    setCollapsed(false);
    setIsModalOpenUnregister(false);
  };

  const handleCancelUnregister = () => {
    clickout?.();
    setIsModalOpenUnregister(false);
  };

  // Delete Modal
  const handleOkDel = () => {
    clickout?.();
    setCollapsed(true);
    setIsModalOpenDel(false);
    // todo: call delete api here
    // 用于判断删除LPN跳转回list页面
    onStateDelChange?.(true);
  };

  const handleCancelDel = () => {
    setCollapsed(false);
    setIsModalOpenDel(false);
  };

  const handleSwitchChange = (checked: boolean) => {
    setCollapsed(!checked);
    if (isDelLPN) {
      if (collapsed) {
        setIsModalOpenDel(false);
      } else {
        setIsModalOpenDel(true);
      }
    } else {
      if (collapsed) {
        setIsModalOpenUnregister(false);
      } else {
        setIsModalOpenUnregister(true);
      }
    }
  };

  const handleUploadSuccess = (response: any) => {
    console.log(response, "response11");
    setIsUploaded(true);
  };

  // view sample document modal
  const handleCancelViewDoc = () => {
    setIsModalOpenViewDoc(false);
  };

  const handleClickViewDoc = () => {
    console.log("Form values handleClickViewDoc");
    setIsModalOpenViewDoc(true);
  };

  // const handleUploadError = () => {
  //   setIsUploaded(false);
  //   setUploadedFile(null);
  // };

  // const handleDeleteUpload = () => {
  //   setIsUploaded(false);
  //   setUploadedFile(null);
  // };
  // Modification Limit Exceeded Modal
  const handleLpnChange = (e: any) => {
    // console.log("Form values handleLpnChange initialValue===", initialValue);
    console.log("Form values handleLpnChange newValue===", e.target.value);
    if (isShowModifyLimitModal && approvalStatus === "Approved") {
      setIsModalOpenModifyLimit(true);
    }
    // setCurrentValue(e.target.value);
  };

  const handleOkModifyLimit = () => {
    setIsShowModifyLimitModal(false);
    setIsModalOpenModifyLimit(false);
  };

  const handleCancelModifyLimit = () => {
    setIsModalOpenModifyLimit(false);
    // setCurrentValue(initialValue);
  };

  return (
    <>
      <Collapse className="collapse-upload" activeKey={collapsed ? [] : ["1"]}>
        <Panel
          header={
            <div style={{ display: "flex", alignItems: "center" }}>
              {/* <Icon width='40px' height='40px' component={Privatecar} style={{ fill: 'blue' }} /> */}
              <img src={icon} alt="My SVG Icon" />

              <span style={{ marginLeft: "12px" }}>{leftText}</span>
              <Switch
                checked={!collapsed}
                onChange={handleSwitchChange}
                style={{ marginLeft: "auto" }}
              />
            </div>
          }
          key="1"
        >
          {formName === "LGV" && (
            <CustomAlert
              type="info"
              // icon={<span style={{ color: "green" }}>✓</span>}
              // borderColor="#998065"
              // titleColor="#7A6145"
              // descriptionColor="#7A6145"
              icon={AlertCircle}
              message="Vehicle Size Restriction"
              // backgroundColor="#F7F5F1"
              showIcon={true}
              description={
                "All Light Goods Vehicle cannot exceed 10.0 meters (Overall Length) and 3.5 meters (Overall Height) at any Airport Authority Carparks."
              }
              style={{ marginBottom: "20px" }}
            />
          )}
          <Row>
            <Col span={12}>
              <div className="lpn-text">
                <ProFormText
                  // rules={[
                  //   {
                  //     required: true,
                  //   },
                  // ]}
                  width="md"
                  name={[`${formName}`, "lpnNoInput"]}
                  placeholder={"Please Enter"}
                  label={
                    <LabelToolTip
                      label="License Plate Number"
                      tooltipTitle={`Restricted to the letters "I", "O" and "Q".`}
                    />
                  }
                  // initialValue={initialValue}
                  fieldProps={{
                    onChange: handleLpnChange,
                  }}
                />
                {/* {approvalStatus === "Approved" && (
                  <StyleApprovedStatusSpan className="status-span">
                    Approved
                  </StyleApprovedStatusSpan>
                )}
                {approvalStatus === "Decline" && (
                  <StyleDeclineStatusSpan className="status-span">
                    Decline
                    <StyledAlertCircle />
                  </StyleDeclineStatusSpan>
                )}
                {approvalStatus === "Expired" && (
                  <StyleExpiredStatusSpan className="status-span">
                    Expired
                  </StyleExpiredStatusSpan>
                )} */}
              </div>
            </Col>
            <Col span={12}>
              <ProFormText
                width="md"
                name={[`${formName}`, "octopus"]}
                placeholder={"Please Enter"}
                label="Octopus No. (Exclude the number in the bracket)"
              />
            </Col>
          </Row>

          <Row>
            <Col span={12}>
              <ProFormText
                width="md"
                name={[`${formName}`, "lpnNo"]}
                placeholder={"Please Enter"}
                label={
                  <LabelToolTip
                    label="Confirm License Plate Number"
                    tooltipTitle={`Restricted to the letters "I", "O" and "Q".`}
                  />
                }
              />
            </Col>
            <Col span={12}>
              <ProFormText
                width="md"
                name={[`${formName}`, "octopus"]}
                placeholder={"Please Enter"}
                label="Confirm Octopus No. (Exclude the number in the bracket)"
              />
            </Col>
          </Row>

          <StyledNone>
            <ProFormText
              width="md"
              name={[`${formName}`, "vehType"]}
              initialValue={formName}
              fieldProps={{ defaultValue: formName }}
            />
          </StyledNone>
          <div className="upload-text">
            Please upload Vehicle Registration Document{" "}
            {formName === "privateCar" && isUploaded && (
              <span onClick={handleClickViewDoc} className="highlight-text">
                View Sample Document
              </span>
            )}
          </div>
          <ProFormUploadDragger
            className="formUpload"
            max={1}
            title={
              <>
                Drag or{" "}
                <span style={{ color: "#7A6145", textDecoration: "underline" }}>
                  Browse
                </span>
              </>
            }
            icon={<img src={upload} alt="upload" />}
            description={`The file size cannot exceed 5MB.\n
Acceptable formats for submission: PDF, PNG and JPG.`}
            fieldProps={{
              // fileList: Array.isArray(fileList) ? fileList : [],
              itemRender: (_, file, __, remove) => (
                <>
                  <Card
                    className="procard11"
                    style={{
                      maxWidth: "50%",
                      marginTop: "10px",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                    }}
                    hoverable
                    bordered
                    styles={{
                      body: { width: "100%" }, // 使用 styles.body 替代 bodyStyle
                    }}
                  >
                    <FileContainer>
                      <FileImage src={FileUpload} alt="FileUpload" />
                      <FileInfo>
                        <FileName className="file-name">{file.name}</FileName>
                        <FileSize className="file-size">{fileSize}</FileSize>
                      </FileInfo>
                      <CloseOutlined
                        onClick={() => {
                          remove.remove(); // 调用 remove 方法
                          setIsUploaded(false); // 更新上传状态
                        }}
                        style={{ marginLeft: "auto", fontSize: "24px" }}
                      />
                    </FileContainer>
                  </Card>
                </>
              ),
              multiple: false,
              onChange: (info) => {
                if (info?.fileList?.length > 1) {
                  info?.fileList?.shift();
                }
                if (info?.fileList?.length > 0) {
                  const file = info?.fileList?.[0]?.originFileObj;
                  if (file !== undefined) {
                    const sizeInBytes = file.size;
                    const sizeInKB = sizeInBytes / 1024;
                    const sizeInMB = sizeInKB / 1024;

                    let sizeText;
                    if (sizeInMB > 1) {
                      sizeText = `${sizeInMB.toFixed(2)} MB`;
                    } else if (sizeInKB > 1) {
                      sizeText = `${sizeInKB.toFixed(2)} KB`;
                    } else {
                      sizeText = `${sizeInBytes} bytes`;
                    }
                    setFileSize(sizeText);
                    console.log("Form values==", sizeText);
                  }
                }
              },
              beforeUpload: async (file) => {
                console.log(file, "filebeforeUpload");
                const binaryData = await file.arrayBuffer();
                console.log(binaryData, "binaryData");
                // return false; // 不让组件自动上传，手动上传处理
              },
              customRequest: ({ file, onSuccess }) => {
                // @ts-ignore
                onSuccess({ file });
                handleUploadSuccess({ file });
              },
              accept: ".jpg, .jpeg, .png,.pdf",
            }}
            label=""
            name={[`${formName}`, "vehicle"]}
          ></ProFormUploadDragger>

          <ProFormCheckbox
            name={[`${formName}`, "dppp"]}
            fieldProps={{ onChange: handleCheckboxChange }}
          >
            I have DPP Permit.
          </ProFormCheckbox>
          {showContent && (
            <>
              <UploadTitle>Please upload DPP Permit</UploadTitle>
              <UploadDragger
                required={true}
                childrens={<></>}
                title={"DPP Permit Information"}
                name={[`${formName}`, "dpppFile"]}
              />
            </>
          )}
          <ProFormCheckbox
            name={[`${formName}`, "authLetter"]}
            fieldProps={{ onChange: handleCheckboxChange1 }}
          >
            I am not the vehicle owner.
          </ProFormCheckbox>
          {showContent1 && (
            <>
              <UploadTitle> Please upload Authority Letter</UploadTitle>
              <UploadDragger
                required={true}
                title={"Authority Letter Information"}
                name={[`${formName}`, "authFile"]}
              />
            </>
          )}
        </Panel>
      </Collapse>
      {/* Delete this License Plate Number? modal */}
      <CustomModal
        width="40%"
        icon={alertFill}
        title="Delete this License Plate Number?"
        content="By deleting this licence plate number, the uploaded content will be permanently erased. Once erased, this action cannot be undone."
        onOk={handleOkDel}
        onCancel={handleCancelDel}
        isModalOpen={isModalOpenDel}
        btnLeftText="Cancel"
        btnRightText="Delete"
        btnRightBgColor="#C02020"
        btnRightTextColor="#FFF"
        btnRightHoverBgColor="C02020"
      />
      {/* Unregister License modal */}
      <CustomModal
        width="40%"
        icon={alertFill}
        title="Unregister this License Plate Number?"
        content="Once you unregister this license plate number, the content will be lost and the action cannot be undone."
        onOk={handleOkUnregister}
        onCancel={handleCancelUnregister}
        isModalOpen={isModalOpenUnregister}
        btnLeftText="Unregister"
        btnRightText="Keeping"
      />
      {/* Modification Limit Exceeded modal */}
      <CustomModal
        width="40%"
        icon={alertFill}
        title="Modification Limit Exceeded"
        content="You've modified your License Plate Number more than once this calendar year, requiring additional payment."
        onOk={handleOkModifyLimit}
        onCancel={handleCancelModifyLimit}
        isModalOpen={isModalOpenModifyLimit}
        btnLeftText="Cancel"
        btnRightText="Continue"
      />
      {/* View Sample Document modal */}
      <Modal
        width={"90%"}
        className="submitted-Failed-Modal"
        height={"80%"}
        title=""
        centered
        open={isModalOpenViewDoc}
        footer={null}
        onCancel={handleCancelViewDoc}
      >
        <div className="view-title">Sample of Document Upload</div>
        <div className="view-content">
          <div className="qualified-document">
            <div className="title">Qualified Document</div>
            <div className="description">
              Please upload vertically according to sample specifications.
            </div>
            <div className="content">
              <img src={qualifiedDocument} alt="Qualified Document" />
              <span className="float-text">TBC</span>
            </div>
          </div>
          <Divider type="vertical" className="divider" />
          <div className="unqualified-documen">
            <div className="title">Unqualified Document</div>
            <div className="description">
              e.g. Incomplete Driving Permit, with shading, too much background
              and small photo size
            </div>
            <div className="content">
              <div className="imgList">
                <img src={unqualifiedDocument} alt="UnqualifiedDocument" />
                <img src={unqualifiedDocument} alt="UnqualifiedDocument" />
              </div>
              <span className="float-text">TBC</span>
            </div>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default UploadItem;
